<?php

namespace Trawind\Basics\Traits;

use Trawind\Basics\Enums\BusinessCode;
use Trawind\Basics\Enums\BusinessType;

trait ExceptionTools
{
    static $REPLACE_ATTACHMENT = [
        1 => 'first',
        2 => 'second',
        3 => 'third',
        4 => 'fourth',
        5 => 'fifth',
    ];
    /**
     * @param $error
     * @param $data
     * @param bool $isReplace
     * @return array
     */
    public static function getErrData($error, $data)
    {
        if ($error['message']) {
            $langData = explode(':', $error['message']);
            if (isset($langData[1])) {
                $attributeData = explode(',', $langData[1]);
                foreach ($attributeData as $key => $attribute) {
                    if (isset($error['original']) && $error['original']) {
                        $replaceValue[self::$REPLACE_ATTACHMENT[$key + 1]] = $attribute;
                    } else {
                        $replaceValue['attribute'] = __('validation.attributes.' . $attribute);
                    }
                }
                unset($error['original']);
                if (explode('.', $langData[0])[0] == 'exception') {
                    $error['message'] = ___($langData[0], $replaceValue);
                } else {
                    $error['message'] = __($langData[0], $replaceValue);
                }
            } else {
                if (explode('.', $langData[0])[0] == 'exception') {
                    $error['message'] = ___($langData[0]);
                } else {
                    $error['message'] = __($langData[0]);
                }
            }
        }

        if (!$data) {
            return $error;
        } else if (is_array($data)) {
            return array_merge($data, $error);
        } else if (is_object($data)){
            return array_merge($data->toArray(), $error);
        }

        return $error;
    }
}
